package 剑指offer;

/**
 * @description:
 * @author: ywk
 * @date: 2021-02-07
 */
public class 求补码 {
    public static void main(String[] args) {

        System.out.println(NumberOf1(Integer.MIN_VALUE));

    }

    public static int NumberOf1(int n) {
        if (n == 0) {
            return 0;
        }
        //标志位
        int symbol = 1;
        int first = -1;
        if (n < 0) {
            symbol = -1;
            //减一防止溢出
            n = (n - first) * -1;
        }
        int count = 0;
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            sb.append(n % 2);
            if (n % 2 == 1) {
                count++;
            }
            n = n / 2;
        }
        if (symbol == 1) {
            return count;
        } else {
            char[] arr = sb.toString().toCharArray();
            int add = 0;
            count = 0;
            for (int i = 30; i >= 0; i--) {
                int num = 0;
                int temp = arr.length - 1 - (30 - i);
                if (temp < arr.length) {
                    if (temp >= 0) {
                        num = Integer.parseInt(String.valueOf(arr[temp]));
                    }
                }
                if (num == 0 && arr.length > 0) {
                    num = 1;
                } else {
                    num = 0;
                }
                if (temp == arr.length - 1 && arr.length > 0) {
                    num += 1;
                }
                num += add + 1;
                add = num / 2;
                num = num % 2;
                if (num == 1) {
                    count++;
                }
            }
            //加上符号位
            return count + 1;
        }
    }

}
